import React from 'react';
// 代理地址 --> "proxy": "http://www.weather.com.cn/";

class Weather extends React.Component {
  state = {
      cityList:[
          {name:"北京",code:101010100},
          {name:"昌平-北京",code:101010700},
          {name:"杭州",code:101210101},
          {name:"苏州",code:101190401},
          {name:"上海",code:101020100},
          {name:"汕头",code:101280501},
          {name:"沈阳",code:101070101},
          {name:"大连",code:101070201},
          {name:"阜新",code:101070901},
        ],
      weather: null
  }

    getCityWeather(i){
        if(i < 0) return this.setState({ weather: null});

        const url = `/data/cityinfo/${this.state.cityList[i].code}.html`;
        fetch(url).then(res => {
            res.json().then(resJson => {
                this.setState({ weather: resJson.weatherinfo });
            })
        })
    }

  render () {
    let selectItem = this.state.cityList.map((it,i)=>{
        return <option key={i} value={i} style={{fontSize:"12px"}} >{it.name}</option>
    });

    selectItem.unshift(<option key={-1} value="-1" style={{fontSize:"12px"}} >~ 请选择查询城市 ~</option>)

    const {  weather } = this.state;
    return (
      <div style={
          {width:"100vw",height:"100vh",backgroundColor:"skyblue",fontSize:"20px",padding:"20px"}
      }>
          <h2 style={{textAlign:"center",fontSize:"20px",fontWeight:"900",lineHeight:"2"}}>
            <button onClick={()=>{this.props.history.go(-1)}}>back</button>
            天气查询
          </h2>
          
          <div>
              <select onChange={(e)=>{this.getCityWeather(e.target.value)}} 
                style={{fontSize:"16px"}}
              >
                  {selectItem}
              </select>
          </div>

        { this.state.weather
          ? <ul style={
              {backgroundColor:"#fff",padding:"10px 30px",borderRadius:"10px",margin:"20px 0",fontSize:"16px"}
          }>
              {/* <li>city: { weather.city }</li> */}
              {/* <li>cityid: { weather.cityid }</li> */}
              {/* <li>ptime: { weather.city }</li> */}
              <li>城市: { weather.city }</li>
              <li>日期: { new Date().toLocaleDateString() }</li>
              <li>天气: { weather.weather }</li>
              <li>最高温度: { weather.temp2 }</li>
              <li>最低温度: { weather.temp1 }</li>
            </ul>
             : <p style={{textAlign:"center",color:"#666",lineHeight:"4"}}>~ 请选择查询城市 ~</p>
        }
      </div>
    )
  }
}

export default Weather